<template>
  <div class="flex-row nav-bar-container">
    <div :key="`nav-bar-item-${i}`"
         class="item"
         style="itemStyles"
         @click="onNav(i,item)" v-for="(item,i) of bars">
      {{ item.label }}
    </div>
    <div class="bar" :style="barStyles"></div>
  </div>
</template>

<script lang="ts">
import {defineComponent, PropType} from "vue";
import {isEmpty} from "@/utils/helpers";

export default defineComponent({
  name: "CNavBar",
  emits: [
    'onNav'
  ],
  props: {
    bars: {
      required: true,
      type: Array as PropType<any[]>,
      default: () => []
    },
    barPadding: {
      type: Number,
      default: 5,
    },
    index: Number,
    itemStyles: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      __index: -1,
    }
  },
  mounted() {
    if (this.bars.length) {
      this.__index = this.index || 0;
    }

  },
  computed: {
    barStyles(): object {
      const index = this.__index, barPadding = this.barPadding;
      if (isEmpty(this.$el)) {
        return {}
      }
      const el: HTMLElement = this.$el.children[index];
      if (isEmpty(el)) {
        return {}
      }
      return {
        left: `${el.offsetLeft + barPadding}px`,
        width: `${el.offsetWidth - 2 * barPadding}px`,
      }
    }
  },
  methods: {
    onNav(index: number, item: any) {
      this.__index = index
      this.$emit('onNav', {item, index});
    }
  }
})
</script>

<style lang="less" scoped>
.nav-bar-container {
  position: relative;

  .item {
    padding: 0 10px;
    line-height: 50px;
    font-size: 16px;
  }

  .bar {
    background-color: #FA3C32;
    width: 0;
    height: 5px;
    border-radius: 10px;
    position: absolute;
    bottom: 0;
    transition: all 100ms;
  }
}
</style>